#include "musiclist.h"
#include <QMimeDatabase>

MusicList::MusicList()
{

}

void MusicList::addMusicsByUrl(const QList<QUrl> &fileUrls)
{
    for(auto& it : fileUrls){
        bool flag = false;
        for(auto& music : list){
            if(music->getUrl() == it){
                flag = true;
                break;
            }
        }
        if(flag) continue;
        //检查e是否是一个合法的音频文件
        QMimeDatabase mimeDB;
        QMimeType mimeType = mimeDB.mimeTypeForFile(it.toLocalFile());
        QString type = mimeType.name();
        if (type.startsWith("audio/"))
        {
            Music* obj = new Music(it);
            list.push_back(obj);
        }
    }
}

QVector<Music*>::iterator MusicList::begin()
{
    return list.begin();
}

QVector<Music*>::iterator MusicList::end()
{
    return list.end();
}

void MusicList::addMusicToDB()
{
    for(auto& it : list){
        it->insertMusicToDB();
        delete it;
    }
}

void MusicList::readMusicFromDB()
{
    QSqlQuery query;
    query.prepare("SELECT musicId, musicName, musicSinger,musicAlbum,\
                    musicUrl, duration, isLike, isHistory FROM QQMusicInfo");
    if(!query.exec()){
        qDebug() << "数据查询失败\n";
        return;
    }
    while(query.next()){
        Music *music = new Music();
        music->setUuid(query.value(0).toString());
        music->setName(query.value(1).toString());
        music->setSinger(query.value(2).toString());
        music->setAlbum(query.value(3).toString());
        music->setUrl(query.value(4).toString());
        music->setSongTime(query.value(5).toLongLong());
        music->setIsLike(query.value(6).toBool());
        music->setIsHistory(query.value(7).toBool());
        list.push_back(music);
    }
}

